﻿using System;
using System.IO;
using Microsoft.SharePoint;
using Spring.Core.IO;

namespace Collaboris.Saf.Repositories.SpringExtensions.Core.IO
{
    /// <summary>
    /// This allows a file in a Document Library to be exposed 
    /// as a Spring Resource.
    /// </summary>
    /// <remarks>
    /// The resource can easily be defined by using a resource key like this :
    ///   - sharepoint://localhost/shareddocs/somefile.xml
    /// 
    /// This class will attempt to use the SPContext to get the file. 
    /// NOTE! If the SPContext is null then this can be refactored to 
    /// create an new SPSite. (Watchout for disposal though).
    /// </remarks>
    /// <remarks>
    /// Please Note, in order to get this working the Resource needs to be 
    /// declated in App|Web.Config.
    /// </remarks>
    /// <example>
    /// <?xml version="1.0" encoding="utf-8" ?>
    /// <configuration>
	///     <configSections>
	///         <sectionGroup name="spring">
    /// 
    ///             <section name="resourceHandlers"
	/// 	            type="Spring.Context.Support.ResourceHandlersSectionHandler, Spring.Core"/>
    /// 
    ///         </sectionGroup>
	///     </configSections>
    /// 
	///     <spring>
	/// 	    <resourceHandlers>
	/// 		    <handler protocol="sharepointuri" 
    /// 				 type="Collaboris.Saf.Repositories.SpringExtensions.Core.IO, Collaboris.Saf"/>
    /// 	    </resourceHandlers>
	/// 	
	///     </spring>
    /// </configuration>
    /// </example>
    public class SharePointUriResource : AbstractResource
    {
        private string folderUrl;

        /// <summary>
        /// Initializes a new instance of the <see cref="SharePointUriResource"/> class.
        /// </summary>
        /// <param name="resourceName">Name of the resource.</param>
        public SharePointUriResource(string resourceName)
            : base(resourceName)
        {
            if (SPContext.Current == null)
                throw new NullReferenceException("There is no SharePoint Context accessible.");

            this.folderUrl = resourceName.ToLower().Replace("sharepoint", "http");
        }

        /// <summary>
        /// Stream returned from the file
        /// </summary>
        public override Stream InputStream
        {
            get
            {
                SPFile file = SPContext.Current.Web.GetFile(this.folderUrl);
                return file.OpenBinaryStream();
            }
        }

        /// <summary>
        /// Description of the File
        /// </summary>
        public override string Description
        {
            get
            {
                SPFile file = SPContext.Current.Web.GetFile(this.folderUrl);
                return file.Item.Title;
            }
        }
    }
}